import java.util.Date;
import java.util.concurrent.TimeUnit;
import java.util.concurrent.locks.Condition;
import java.util.concurrent.locks.ReentrantLock;

public class Chefwaiter {
    private ReentrantLock lock = new ReentrantLock();
    private Condition chefCondition = lock.newCondition();
    private Condition waiterCondition = lock.newCondition();
    class Chef implements Runnable {
        private Waiter waiter;
        public void setWaiter(Waiter waiter){
            this.waiter = waiter;
        }
        public void run(){
            while(true){
                lock.lock();
                try{
                    chefCondition.await();
                    System.out.println("厨师收到waiter下单后，做菜...");
                    int rand = (int)(Math.random()*1000);
                    Thread.sleep(rand);
                    System.out.println(rand+"毫秒后，厨师通知waiter取餐...");
                    waiterCondition.signal();
                } catch (InterruptedException e) {
                    e.printStackTrace();
                } finally {
                    lock.unlock();
                }
            }
        }
    }
    class Waiter implements Runnable{
        private Chef chef;
        public void setChef(Chef chef){
            this.chef = chef;
        }
        public void run(){
            while(true){
                lock.lock();
                try{
                    int rand = (int)(Math.random()*1000);
                    Thread.sleep(rand);
                    System.out.println(rand+"毫秒后waiter接到下单，通知厨师做菜...");
                    chefCondition.signal();
                    waiterCondition.await();
                    System.out.println("接到厨师通知，waiter取餐...");

                } catch (InterruptedException e) {
                    e.printStackTrace();
                }finally {
                    lock.unlock();
                }
            }
        }
    }
    public void startWork(){
        Chef chef = new Chef();
        Waiter waiter = new Waiter();
        chef.setWaiter(waiter);
        waiter.setChef(chef);
        new Thread(chef).start();
        new Thread(waiter).start();
    }

    public static void main(String[] args) {
        Chefwaiter cw = new Chefwaiter();
        cw.startWork();
    }
}
